<?php
class ForgotPassword extends Module
{
	function ForgotPassword($row){
		Module::Module($row);

		$user_id = 	(int)Url::get('id');
		
		if($user_id){
			$user = DB::fetch("SELECT user_name,email FROM account WHERE id=$user_id");
			
			if($user && md5($user['user_name'].$user['email'])==Url::get('u')){
				
				$new_password = $this->random_string();
				$user_name = $user['user_name'];
				$subject = 'Khôi phục mật khẩu thành công!';
				$messenger=file_get_contents('templates/ForgotPassword/reset_password.html');
				$message=str_replace('[[|user_name|]]',$user_name,$messenger);
				$message=str_replace('[[|password|]]',$new_password,$message);
				
				if(System::sendECEmail($user['email'],$subject,$message)){
					DB::update('account',array('password'=>User::encode_password($new_password)),"id=$user_id");
					
					Url::redirect_current(array('action'=>'reset_success'));
				}
				else{
					Url::redirect_current(array('action'=>'reset_error'));
				}
			}
			else{
				Url::redirect('home');
			}
		}
		
		require_once 'forms/forgot_password.php';
		$this->add_form(new ForgotPasswordForm);
	}
	
	function random_string(){
		$len = 8;
		$base='ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz123456789';
		$max=strlen($base)-1;
		$activatecode='';
		mt_srand((double)microtime()*1000000);
		while (strlen($activatecode)<$len+1)
		  $activatecode.=$base{mt_rand(0,$max)};		  
		return $activatecode;
	}
}
?>